package org.iks.gfs.business.controller;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.iks.common.AjaxResult;
import org.iks.gfs.business.service.GfsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * Author kzou
 * Date 2024/2/14
 * Description: 文件服务
 */
@RequestMapping
@RestController
public class GfsController {

    @Autowired
    private GfsService gfsService;

    @PostMapping("upload")
    public AjaxResult<?> updateImage(MultipartFile file, HttpServletRequest request) {
        String fileName = gfsService.uploadFile(file);
        return AjaxResult.success(fileName);
    }

    @GetMapping("preview/{fileName}")
    public void previewImage(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
        byte[] data = gfsService.loadImage(fileName);
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength(data.length);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName );
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(data);
        response.flushBuffer();
    }

}
